package movie.controller;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import movie.entity.Consumer;
import movie.service.LoginService;

@Controller
public class LoginController {
	@Autowired
	private LoginService loginService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String get(HttpServletRequest request, Model model) {
		model.addAttribute("login_error", 0);
		HttpSession session = request.getSession();
		if(session.getAttribute("cur_user") != null) {
			return "redirect:/home";
		}
		else return "/user/login";
	}
	
	@RequestMapping(value = "/logoff", method = RequestMethod.GET)
	public String get2(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		session.removeAttribute("cur_user");
		return "redirect:/home";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String post(Consumer consumer,HttpServletRequest request, Model model) {
		
		Consumer consumer1 = loginService.Login(consumer);
		if(consumer1 != null) {//成功
			
			if(consumer1.getPassWord().equals(consumer.getPassWord())) {
				
				Calendar calendar = Calendar.getInstance();
				Date curTime = calendar.getTime();
				Date termTime = consumer1.getMemberDate();
				
				if(curTime.after(termTime)) {
					Calendar c = Calendar.getInstance();
					c.set(2099, 1, 1);
					termTime = c.getTime();
					consumer1.setMemberId(1);
					consumer1.setMemberDate(termTime);
					loginService.update_member(consumer1);
				}
				
				HttpSession session = request.getSession();
	            session.setAttribute("cur_user", consumer1);
	            session.setMaxInactiveInterval(15*60);
	            model.addAttribute("login_error", 0);
				return "redirect:/home";
			}
			else{//密码错误
				model.addAttribute("login_error", 1);
				return "/user/login";//重定向
			}
		}

		else {//未注册
			model.addAttribute("login_error", 1);
			return "/user/login";
		}
		//forward
	}

}
